<template>
  <el-form ref="loginFormRef" :model="loginForm" :rules="loginRules" size="large">
    <el-form-item prop="username">
      <el-input v-model="loginForm.username" placeholder="用户名">
        <template #prefix>
          <el-icon class="el-input__icon">
            <user />
          </el-icon>
        </template>
      </el-input>
    </el-form-item>
    <el-form-item prop="password">
      <el-input v-model="loginForm.password" type="password" placeholder="密码" show-password autocomplete="new-password">
        <template #prefix>
          <el-icon class="el-input__icon">
            <lock />
          </el-icon>
        </template>
      </el-input>
    </el-form-item>

    <el-form-item prop="captcha" style="display: flex">
      <div style="width: calc(100% - 200px)">
        <el-input v-model="loginForm.captcha" placeholder="验证码">
          <template #prefix>
            <el-icon class="el-input__icon">
              <connection />
            </el-icon>
          </template>
        </el-input>
      </div>
      <div class="captcha-img" @click="getCaptchaImg()">
        <img :src="captchaImg" />
      </div>
    </el-form-item>
  </el-form>
  <div class="login-btn">
    <el-button :icon="CircleClose" round size="large" @click="resetForm(loginFormRef)"> 重置 </el-button>
    <el-button :icon="UserFilled" round size="large" type="primary" :loading="loading" @click="login(loginFormRef)">
      登录
    </el-button>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from "vue";
import { useRouter } from "vue-router";
import { HOME_URL } from "@/config";
import { getTimeState } from "@/utils";
import { Login } from "@/api/interface";
import { ElNotification } from "element-plus";
import { CircleClose, UserFilled } from "@element-plus/icons-vue";
import type { ElForm } from "element-plus";
import md5 from "md5";
import { useUserStore } from "@/stores/modules/user";
const userStore = useUserStore();
type FormInstance = InstanceType<typeof ElForm>;
import deepcopy from "deepcopy";
import { useTabsStore } from "@/stores/modules/tabs";
import { useKeepAliveStore } from "@/stores/modules/keepAlive";
import { getCaptcha } from "@/api/modules/login";
const loginFormRef = ref<FormInstance>();
const loginRules = reactive({
  username: [{ required: true, message: "请输入用户名", trigger: "blur" }],
  password: [{ required: true, message: "请输入密码", trigger: "blur" }],
  captcha: [
    { required: true, message: "请输入验证码", trigger: "blur" },
    {
      max: 6,
      message: "验证不能大于6个字符",
      trigger: "blur"
    }
  ]
});
const router = useRouter();
const tabsStore = useTabsStore();
const keepAliveStore = useKeepAliveStore();
const captchaImg = ref<string>("");
const loading = ref(false);
const loginForm = reactive<Login.DoLoginFrom>({
  username: "",
  password: "",
  captchaId: "",
  captcha: ""
});
const getCaptchaImg = () => {
  getCaptcha().then(({ data }) => {
    loginForm.captchaId = data.id;
    captchaImg.value = data.img;
  });
};
// login
const login = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.validate(async valid => {
    if (!valid) return;
    loading.value = true;
    const param = deepcopy(loginForm) as Login.DoLoginFrom;
    param.password = md5(param.username + param.password);
    userStore
      .doLong(param)
      .then(() => {
        tabsStore.closeMultipleTab();
        keepAliveStore.setKeepAliveName();
        router.push(HOME_URL);
        ElNotification({
          title: getTimeState(),
          message: "欢迎登录 使用『" + import.meta.env.VITE_GLOB_APP_TITLE + "』管理端",
          type: "success",
          duration: 3000
        });
      })
      .catch(() => {
        getCaptchaImg();
        loginForm.captcha = "";
      })
      .finally(() => {
        loading.value = false;
      });
  });
};

// resetForm
const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.resetFields();
};

onMounted(() => {
  getCaptchaImg(); //初始化验证码
  // 监听 enter 事件（调用登录）
  document.onkeydown = (e: KeyboardEvent) => {
    e = (window.event as KeyboardEvent) || e;
    if (e.code === "Enter" || e.code === "enter" || e.code === "NumpadEnter") {
      if (loading.value) return;
      login(loginFormRef.value);
    }
  };
});
</script>

<style scoped lang="scss">
@import "../index.scss";
</style>
